﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebAPITest.Models;
using WebAPITest.Models.Database;
using WebAPITest.Models.service;

namespace WebAPITest
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        //注入jwt服务
        private readonly IJWTService _jwtService;
        private readonly WebEnterpriseIIContext _db;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtService"></param>
        public AuthenticationController(IJWTService jwtService, WebEnterpriseIIContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        /// <summary>
        /// 创建token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string CreateToken(string name)
        {
            return _jwtService.CreateToken(name, 0, "", "");
        }
        [Authorize]
        [HttpGet]
        public void Test()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public object UserInfo()
        {
            //通过userId查询数据库数据 
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            return user;
        }

        //注册 输入用户信息 添加到数据
        [HttpPost]
        public string Reg(RegRequest request)
        {
            if (_db.Users.Any(x => x.UserName == request.UserName))
            {
                return "用户存在";
             }
            var user = new User()
            {
                UserName = request.UserName,
                Email = request.Email,
                NickName = request.NickName,
                Password = request.Password,
                UserLevel = 1,
                Salt = 0,
                CreateTime=DateTime.Now,
                //UserLevel = 1,

        };
        _db.Users.Add(user);
            //保存更改
            var row= _db.SaveChanges();
            if (row > 0)
            {
                return "注册成功";
            }
            return "注册失败";
        }
        [HttpPost]
        public string Login(string username,string password)
        {
            //判断密码是否正确
            var user = _db.Users.FirstOrDefault(x => x.UserName == username);
                if (user == null)
                return "用户不存在";
                if(user.Password!=password)
            {
                return "密码不正确";
            }
            return _jwtService.CreateToken(user.UserName, user.UserId, user.Email, user.NickName);
        }
    }
}
